package com.agileai.esb.smc.controller.sysres;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import javax.wsdl.Definition;
import javax.wsdl.Port;
import javax.wsdl.Service;
import javax.wsdl.WSDLException;
import javax.wsdl.extensions.ExtensibilityElement;
import javax.wsdl.extensions.http.HTTPAddress;
import javax.wsdl.extensions.soap.SOAPAddress;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.wsdl.xml.WSDLWriter;
import com.agileai.domain.*;
import com.agileai.esb.smc.bizmoduler.sysres.WsResListManage;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.StandardEditHandler;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;

public class WsResListManageEditHandler
        extends StandardEditHandler {
	
    public WsResListManageEditHandler() {
        super();
        this.listHandlerClass = WsResListManageListHandler.class;
        this.serviceId = buildServiceId(WsResListManage.class);
    }

	public ViewRenderer prepareDisplay(DataParam param) {
		String operaType = param.get(OperaType.KEY);
		DataRow record = new DataRow();
		if (isReqRecordOperaType(operaType)){
			record = getService().getRecord(param);
		}
		record.put("WS_GRP_ID", param.getString("WS_GRP_ID"));
		record.put("WS_GRP_NAME", param.getString("WS_GRP_NAME"));
		
		this.setAttributes(record);	
		this.setOperaType(operaType);
		return new LocalRenderer(getPage());
	}
    
    @SuppressWarnings("unchecked")
	@PageAction
	public ViewRenderer fillForm(DataParam param) {
    	DataRow record = new DataRow();
		String fillWay = param.getString("FILL_WAY");
		String wsAddr = param.getString("WS_ADDR");
		WSDLFactory factory = null;
		WSDLWriter writer = null;
		WSDLReader reader = null;
		Definition definition = null;
		OutputStream output = null;

		try {
			factory = WSDLFactory.newInstance();
			writer = factory.newWSDLWriter();
			reader = factory.newWSDLReader();
			
			//地址填充方式
			if (fillWay.equals("0")) {
				definition = reader.readWSDL(wsAddr);
			//文件填充方式
			} else if (fillWay.equals("1")) {
				definition = reader.readWSDL(null, wsAddr);
			}
			
			//解析文件
			String serviceName = null;
			Map<String, Service> serviceMap = definition.getServices();
			for (Map.Entry<String, Service> entryService : serviceMap.entrySet()) {
				Service service = (Service) entryService.getValue();
				Map<String, Port> ports = service.getPorts();
				serviceName = service.getQName().getLocalPart();
				log.info("[Service Name]:" + serviceName);
				record.put("WS_NAME", serviceName);
				record.put("WS_ALIAS", serviceName);
				
				for (Map.Entry<String, Port> entryPort : ports.entrySet()) {
					Port port = (Port) entryPort.getValue();
					List<ExtensibilityElement> portExtList = port.getExtensibilityElements();
					ExtensibilityElement extElemet = portExtList.get(0);
					if (extElemet instanceof SOAPAddress) {
						SOAPAddress soapAddress = (SOAPAddress) extElemet;
						log.info("[Service Location URI]:" + soapAddress.getLocationURI());
						record.put("WS_LOCATION", soapAddress.getLocationURI());
					} else if (extElemet instanceof HTTPAddress) {
						HTTPAddress httpAddress = (HTTPAddress) extElemet;
						log.info("[Service Location URI]:" + httpAddress.getLocationURI());
						record.put("WS_LOCATION", httpAddress.getLocationURI());
					}
				}
			}

			//写入文件
			String filePath = File.separator + "reponsitory" + File.separator + "wsdl"+ File.separator + serviceName + ".wsdl";
			output = new FileOutputStream(new File(getWSDLFilePath() + filePath));
			writer.writeWSDL(definition, output);
			
			record.put("WS_FILE_PATH", filePath);
			record.put("WS_GRP_ID", param.getString("WS_GRP_ID"));
			record.put("WS_GRP_NAME", param.getString("WS_GRP_NAME"));
		} catch (WSDLException e) {
			e.printStackTrace();
			setErrorMsg(e.getLocalizedMessage());
			log.error(e.getLocalizedMessage());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			setErrorMsg(e.getLocalizedMessage());
			log.error(e.getLocalizedMessage());
		} finally {
			try {
				if (output != null) {
					output.flush();
					output.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				log.error(e.getLocalizedMessage());
			}
		}
		
		setOperaType(OperaType.CREATE);
		this.setAttributes(param);
		this.setAttributes(record);
		return new LocalRenderer(getPage());
	}
    
	public String getWSDLFilePath(){
		String result = null;
		String realPath = request.getServletContext().getRealPath("/");
		String tempPath = realPath.replaceAll("\\\\", "/");
		if (tempPath.endsWith("/")){
			tempPath = tempPath.substring(0, tempPath.length()-1);
		}
		tempPath = tempPath.substring(0, tempPath.lastIndexOf("/"));
		result = tempPath.substring(0, tempPath.lastIndexOf("/"));
		return result;
	}	

    protected WsResListManage getService() {
        return (WsResListManage) this.lookupService(this.getServiceId());
    }
}
